/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);

var app = new Vue({
    el: '#app',
    data: {
        permissions: ['app:add', 'app:update'],//本页权限数组
        selects: [],
        desc: '',
        schoolId: schoolId,
        schoolList: schoolMap,
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);

            return;
        }
        if (!empty(aGET.id)) {
            that.getInfoById(aGET.id);
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        getInfoById: function (id) {
            var that = this;
            Get(that, _HOST + _API.business_app_getById + "?id=" + id)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            var list = response.data;
                            var oldMpQrCodeId = "";
                            var oldMiniappQrCodeId = "";
                            for (var item in list) {
                                if (item == 'mpQrCode') {
                                    oldMpQrCodeId = list[item];
                                }
                                if (item == 'miniappQrCode') {
                                    oldMiniappQrCodeId = list[item];
                                }
                                if (item == 'mpQrCodeIdUrl') {
                                    initMpFileUpload(list[item]);
                                }
                                if (item == 'miniappQrCodeUrl') {
                                    initMaFileUpload(list[item]);
                                }
                                $("#Form input[name='" + item + "']").val(list[item]);
                            }
                            $("#Form input[name='oldMpQrCodeId']").val(oldMpQrCodeId);
                            $("#Form input[name='oldMiniappQrCodeId']").val(oldMiniappQrCodeId);
                            $("#Form").data('bootstrapValidator').destroy();
                            $('#Form').data('bootstrapValidator', null);
                            Validator();
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        },
        // 添加
        add: function () {
            var that = this;
            var param = formToJson($("#Form").serialize());
            if (!empty(aGET.companyId)) {
                param['companyId'] = aGET.companyId;
            }
            //console.log(param)
            Post(that, _HOST + _API.business_app_add, param, true, that.permissions[0])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        // 修改
        update: function () {
            var that = this;
            var param = formToJson($("#Form").serialize());
            // console.log(param)
            Post(that, _HOST + _API.business_app_update, param, true, that.permissions[1])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
    },
});

function initMpFileUpload(url) {
    $("#mpFileUpload").fileinput({
        language: "zh",
        uploadUrl: _HOST + _API.common_file_ossUpload,
        ajaxSettings: {
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': ''
            }
        },
        browseClass: "btn btn-success",
        browseLabel: "上传预览图片",
        browseIcon: "<i class=\"glyphicon glyphicon-picture\"></i> ",
        allowedFileExtensions: ['jpg', 'gif', 'png'],
        showUpload: false,
        dropZoneEnabled: true,
        showPreview: true,
        minFileCount: 1,
        maxFileCount: 1,
        initialPreviewAsData: true,
        initialPreview: [
            url
        ],
        initialPreviewConfig: [
            {
                caption: url,
                size: 329892,
                width: "120px",
                url: url,
                key: 1
            },
        ]
    }).on("filebatchselected", function (event, files) {
        $(this).fileinput("upload");
    }).on("fileuploaded", function (event, data, previewId, index) {
        if (data.response.status) {
            $(".file-caption-name").text(data.response.attachemId);
            $("#mpQrCode").val(data.response.attachemId);
        } else {
            parent.layer.msg(data.response.msg, {time: 1500, icon: 5});
        }
    });
    $(".kv-file-remove").remove();
}

function initMaFileUpload(url) {
    $("#maFileUpload").fileinput({
        language: "zh",
        uploadUrl: _HOST + _API.common_file_ossUpload,
        ajaxSettings: {
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': ''
            }
        },
        browseClass: "btn btn-success",
        browseLabel: "上传预览图片",
        browseIcon: "<i class=\"glyphicon glyphicon-picture\"></i> ",
        allowedFileExtensions: ['jpg', 'gif', 'png'],
        showUpload: false,
        dropZoneEnabled: true,
        showPreview: true,
        minFileCount: 1,
        maxFileCount: 1,
        initialPreviewAsData: true,
        initialPreview: [
            url
        ],
        initialPreviewConfig: [
            {
                caption: url,
                size: 329892,
                width: "120px",
                url: url,
                key: 1
            },
        ]
    }).on("filebatchselected", function (event, files) {
        $(this).fileinput("upload");
    }).on("fileuploaded", function (event, data, previewId, index) {
        if (data.response.status) {
            $(".file-caption-name").text(data.response.attachemId);
            $("#miniappQrCode").val(data.response.attachemId);
        } else {
            parent.layer.msg(data.response.msg, {time: 1500, icon: 5});
        }
    });
    $(".kv-file-remove").remove();
}

$(function () {
    if (empty(aGET.id)) {
        initMpFileUpload('');
        initMaFileUpload('');
    }
});

$('#Form').data('bootstrapValidator', null);
Validator();

function Validator() {
    $('#Form').bootstrapValidator({
        fields: {
            mpName: {
                validators: {
                    notEmpty: {
                        message: '请输入微信公众号名称'
                    },
                }
            },
            mpAppId: {
                validators: {
                    notEmpty: {
                        message: '请输入微信公众号id'
                    },
                }
            },
            mpAppSecret: {
                validators: {
                    notEmpty: {
                        message: '请输入微信公众号秘钥'
                    },
                }
            },
            miniappName: {
                validators: {
                    notEmpty: {
                        message: '请输入小程序名称'
                    },
                }
            },
            miniappAppId: {
                validators: {
                    notEmpty: {
                        message: '请输入小程序appid'
                    },
                }
            },
            miniappAppSecret: {
                validators: {
                    notEmpty: {
                        message: '请输入小程序秘钥'
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        // Prevent form submission
        e.preventDefault();
        if (empty(aGET.id)) {
            app.add();
        } else {
            app.update();
        }
    });
}
